package com.xy.realm;

import com.xy.model.User;
import com.xy.service.PermissionService;
import com.xy.service.RoleService;
import com.xy.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;

public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Resource
    PermissionService permissionService;
    /**
     * 授权器
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        /**
         * 授权
         * setRoles 授予该用户是什么角色
         * setStringPermissions 授予改用户的操作权限
         */
        simpleAuthorizationInfo.setRoles(roleService.getRoles(user.getId()));
        simpleAuthorizationInfo.setStringPermissions(permissionService.getPermission(user.getId()));

        return simpleAuthorizationInfo;
    }

    /**
     * 认证器
     * @param token
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String principal = (String) token.getPrincipal();
        String credentials = new String((char[])token.getCredentials());
        User user = userService.getUserByName(principal);
        if(user !=null && user.getUsername().equals(principal) && user.getPassword().equals(credentials)){
            return new SimpleAuthenticationInfo(user,credentials,this.getName());
        }
        return null;
    }
}
